package org.apache.directory.mavibot.btree;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.directory.mavibot.btree.serializer.LongSerializer;

public class BenchMark
{
	public static void main( String[] args ) throws Exception
	{
		if( args.length!=4 )
		{
			System.out.println( "wrong number of arguments" );
			return;
		}
		List<Tuple<Long, Long>> sortedTuple = new ArrayList<Tuple<Long, Long>>();
		File file = File.createTempFile( "managedbtreebuilder", ".data" );
	    file.deleteOnExit();

	    RecordManager rm = new RecordManager( file.getAbsolutePath() );

	    LongSerializer ser = new LongSerializer();
	    PersistedBTreeBuilder<Long, Long> bb = new PersistedBTreeBuilder<Long, Long>( rm, "master", 4, ser,
	        ser );

		int cacheSize=Integer.parseInt(args[1]);
		int nbThread = Integer.parseInt(args[2]);
		Long duration = Long.parseLong(args[3]);
		PersistedBTree<Long, Long> btree = ( PersistedBTree<Long, Long> ) bb.build( sortedTuple.iterator() );
		final CountDownLatch latch = new CountDownLatch( nbThread );
		ArrayList<MyThreadTest> tabThreads = new ArrayList<MyThreadTest>();
		MyThreadTest mythreadTemp;
		FileOutputStream fileOutTime = null;
		OutputStreamWriter oswTime = null;
		BufferedWriter buffTime = null;
		FileOutputStream fileOutValue = null;
		OutputStreamWriter oswValue = null;
		BufferedWriter buffValue = null;
		for ( int i = 0; i < nbThread; i++ )
		{
			mythreadTemp = new MyThreadTest( latch, i, btree, duration,
					cacheSize );
			tabThreads.add( mythreadTemp );
			mythreadTemp.start();
		}
		latch.await();
		int i=1;
		for ( MyThreadTest thread : tabThreads )
		{
			fileOutValue = new FileOutputStream( "threadValue" + i + ".txt" );
			oswValue = new OutputStreamWriter( fileOutValue );
			buffValue = new BufferedWriter( oswValue );
			fileOutTime = new FileOutputStream( "threadTime" + i + ".txt" );
			oswTime = new OutputStreamWriter( fileOutTime );
			buffTime = new BufferedWriter( oswTime );
			for (TimeInsertion timeInsert : thread.getTab())
			{
				buffValue.write(timeInsert.getNbInsertion()+"\n");
				buffTime.write( timeInsert.getDate() + "\n" );
			}
			i++;
			buffTime.close();
			buffValue.close();
		}
	}
}
